<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;

class SystemUser extends Model
{
    use HasFactory,HasApiTokens,Notifiable,HasRoles;
    protected $appends=['department_status'];
    public function guardName(){
        return 'sanctum';
    }
    protected $hidden=['remember_token','password'];
    protected function serializeDate(\DateTimeInterface $date)
    {
        return $date->format('Y/m/d H:i:s');
    }
    protected $guarded = [];
    public function department(){
        return $this->hasOne(Department::class,'id','department_id');
    }
    public function first(){
        return $this->hasOne(Department::class,'id','department_one_id');
    }
    public function two(){
        return $this->hasOne(Department::class,'id','department_two_id');
    }
    public function three(){
        return $this->hasOne(Department::class,'id','department_three_id');
    }
    //客诉数
    protected function departmentStatus(): Attribute
    {
        return new Attribute(
            get: fn () => $this->loginStatus(),
        );
    }
    protected function loginStatus(){
        if(isset($this->attributes['department_three_id'])&&$this->attributes['department_three_id']>0){
            if($this->getDepartmentStatus($this->attributes['department_three_id'])==2){
                return 2;
            }
            if($this->getDepartmentStatus($this->attributes['department_two_id'])==2){
                return 2;
            }
            if($this->getDepartmentStatus($this->attributes['department_one_id'])==2){
                return 2;
            }
        }

        return 1;
    }
    protected function getDepartmentStatus($id){
        return Department::query()->where('id',$id)->value('status');
    }
}
